<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="data_name" label="数据名称" required><uni-easyinput v-model="formData.data_name" /></uni-forms-item>
			<uni-forms-item name="key_name" label="键" required><uni-easyinput v-model="formData.key_name" /></uni-forms-item>
			<uni-forms-item name="value" label="值" required>
				<!-- 文字类型 -->
				<block v-if="formData.config_type == 1"><uni-easyinput v-model="formData.value" /></block>
				<!-- 布尔类型 -->
				<block v-else-if="formData.config_type == 2">
					<uni-data-checkbox v-model="formOptions.config_boolean_val" :localdata="formOptions.config_boolean_localdata" />
				</block>
				<!-- 文件 -->
				<block v-else-if="formData.config_type == 3">
					<uni-file-picker
						ref="files"
						:value="imageValue"
						fileMediatype="image"
						mode="grid"
						:auto-upload="false"
						@select="select"
						@progress="progress"
						@success="success"
						@fail="fail"
						@delete="deleteFile"
					></uni-file-picker>
				</block>

				<!-- 富文本 -->
				<block v-else-if="formData.config_type == 4"><editor-tool :htmlCode="html" ref="editorTool"></editor-tool></block>
			</uni-forms-item>
			<uni-forms-item name="config_type" label="类型"><uni-data-checkbox v-model="formData.config_type" :localdata="formOptions.config_type_localdata" /></uni-forms-item>
			<uni-forms-item name="config_desc" label="说明"><uni-easyinput v-model="formData.config_desc" /></uni-forms-item>

			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button class="uni-button" style="width: 100px;">返回</button></navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
import { validator } from '@/js_sdk/validator/data-config.js';

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'data-config';

function getValidator(fields) {
	let reuslt = {};
	for (let key in validator) {
		if (fields.includes(key)) {
			reuslt[key] = validator[key];
		}
	}
	return reuslt;
}

export default {
	data() {
		return {
			formData: {
				data_name: '',
				key_name: '',
				value: '',
				config_type: null,
				config_desc: ''
			},
			html: '', //富文本初始内容
			formOptions: {
				config_type_localdata: [
					{
						text: '文字',
						value: 1
					},
					{
						text: '布尔',
						value: 2
					},
					{
						text: '文件',
						value: 3
					},
					{
						text: '富文本',
						value: 4
					}
				],
				config_boolean_localdata: [
					{
						text: 'true',
						value: 0
					},
					{
						text: 'false',
						value: 1
					}
				],
				config_boolean_val: 0
			},
			rules: {
				...getValidator(['data_name', 'key_name', 'config_type', 'config_desc'])
			},
			imageValue: [],

			uploadImgs: [] //要上传的图片arr
		};
	},
	onLoad(e) {
		const id = e.id;
		this.formDataId = id;
		this.getDetail(id);
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		/**
		 * 触发表单提交
		 */
		async submit() {
			uni.showLoading({
				mask: true
			});
			if (this.formData.config_type == 3) await this.$refs.files.upload();
			this.$refs.form
				.submit()
				.then(res => {
					this.submitForm(res);
				})
				.catch(errors => {
					uni.hideLoading();
				});
		},

		submitForm(value) {
			switch (value.config_type) {
				case 1:
					value.value += '';
					break;
				case 2:
					value.value = value.value === 0 ? true : false;
					break;
				case 3:
					let imgs = [];
					if (this.imageValue.length > 0) {
						this.imageValue.forEach(item => {
							imgs.push(item.url);
						});
					}
					value.value = this.uploadImgs.concat(imgs);
					break;
				case 4:
					value.value = this.$refs.editorTool.getEditorData();
					break;
			}
			console.log(value);
			// 使用 clientDB 提交数据
			db.collection(dbCollectionName)
				.doc(this.formDataId)
				.update(value)
				.then(res => {
					uni.showToast({
						title: '修改成功'
					});
					this.getOpenerEventChannel().emit('refreshData');
					setTimeout(() => uni.navigateBack(), 500);
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},

		/**
		 * 获取表单数据
		 * @param {Object} id
		 */
		getDetail(id) {
			uni.showLoading({
				mask: true
			});
			db.collection(dbCollectionName)
				.doc(id)
				.field('data_name,key_name,value,config_type,config_desc')
				.get()
				.then(res => {
					const data = res.result.data[0];
					if (data) {
						this.formData = data;
						this.html = data.value;
						try {
							data.value.forEach(item => {
								this.imageValue.push({
									url: item
								});
							});
						} catch (e) {}
					}
				})
				.catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		// 获取上传状态
		select(e) {
			console.log('选择文件：', e);
			// const imgArr = [];
			// e.tempFilePaths.forEach(item => {
			// 	imgArr.push({
			// 		file: item,
			// 		createTime: Date.now()
			// 	});
			// });
			// this.uploadImgs.push(...imgArr);
		},
		deleteFile(e) {
			try {
				this.imageValue.splice(e.index, 1);
			} catch (e) {}
		},
		// 获取上传进度
		progress(e) {
			console.log('上传进度：', e);
		},

		// 上传成功
		success(e) {
			console.log('上传成功', e);
			this.uploadImgs = e.tempFilePaths;
		},

		// 上传失败
		fail(e) {
			console.log('上传失败：', e);
		},
		GetChange(e) {
			console.log(e);
		}
	}
};
</script>
